// Copyright 2010 - eggsy _at_ eggsylife.co.uk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package uk.co.eggsylife.async.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class AsyncHttpClient {

	private static AsyncHttpClient instance = null;
	private HttpClient httpClient = null;
	
	/**
	 * Ensures the class cannot be instantiated
	 */
	private AsyncHttpClient() {
		httpClient = new DefaultHttpClient();
	}
	
	/**
	 * @return The Singleton instance of our {@link AsyncHttpClient}
	 */
	public static AsyncHttpClient getInstance() {
		if(instance == null ) {
			instance = new AsyncHttpClient();
		}
		
		return instance;
	}
	
	public String execute(HttpUriRequest request) {
		HttpResponse response = null;
		String result = null;
		try {
			response =  httpClient.execute(request);
			result = representResponseAsString(response);
		} 
		catch (ClientProtocolException e) {
			Log.e("ERROR", "Unable to connect to client", e);
		} 
		catch (IOException e) {
			Log.e("ERROR", "Unable to convert response to String", e);
		}
		
		return result;
	}
	
	private String representResponseAsString(HttpResponse response) throws IOException{
		BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		String line = null;
		StringBuilder stringBuilder = new StringBuilder();
		while ((line = reader.readLine()) != null) {
			stringBuilder.append(line + "\n");
		}
		
		return stringBuilder.toString();
		
	}
}
